<template>
  <div
    class="pageContain"
    style="color: black; width: 100%; background: #efefef; overflow: hidden"
  >
    <div class="pageContainBack divBeteewn">
      <div class="warningBox" style="width: 57.7%">
        <div class="warningNameBack">告警日志</div>
        <el-table
          :data="dataList"
          max-height="72vh"
          style="height: auto; width: 95%; margin: auto; margin-top: 2vh"
          :header-row-style="{
            height: '6vh',
            fontSize: '1vw',
            color: 'white',
            background: '#005EBC',
          }"
        >
          <el-table-column label="序号" min-width="100">
            <template #default="scope">
              <div>{{ scope.$index + 1 }}</div>
            </template>
          </el-table-column>
          <el-table-column
            label="告警名称"
            prop="warnType"
            align="center"
            min-width="100"
          >
            <template #default="scope">
              <div
                class="warningName"
                v-if="scope.row.warnType == 1"
                @click="skipPage(scope.row.deviceNumber)"
              >
                离线
              </div>
              <div
                class="warningName"
                v-if="scope.row.warnType == 2"
                @click="skipPage(scope.row.deviceNumber)"
              >
                电压丢失
              </div>
              <div
                class="warningName"
                v-if="scope.row.warnType == 3"
                @click="skipPage(scope.row.deviceNumber)"
              >
                电压异常
              </div>
              <div
                class="warningName"
                v-if="scope.row.warnType == 4"
                @click="skipPage(scope.row.deviceNumber)"
              >
                超阀值
              </div>
            </template>
          </el-table-column>
          <el-table-column
            align="center"
            label="设备编号"
            prop="deviceNumber"
            min-width="200"
          ></el-table-column>
          <el-table-column
            align="center"
            label="告警时间"
            prop="warnTime"
            min-width="200"
          ></el-table-column>
          <el-table-column
            label="告警时长"
            prop="durationMinutes"
            align="center"
            min-width="150"
          >
            <template #default="scope">
              <div>{{ convertMinutesToHours(scope.row.durationMinutes) }}</div>
            </template>
          </el-table-column>
          <el-table-column
            label="当前上报等级"
            align="center"
            prop="warnLevel"
            min-width="150"
          >
            <template #default="scope">
              <div v-if="scope.row.warnLevel == 1">一级告警</div>
              <div v-if="scope.row.warnLevel == 2">二级告警</div>
              <div v-if="scope.row.warnLevel == 3">三级告警</div>
            </template></el-table-column
          >
        </el-table>
      </div>

      <div class="warningBox1" style="width: 41%">
        <div class="warningNameBack">告警设置</div>
        <el-table
          :data="warningList"
          max-height="72vh"
          style="height: auto; width: 95%; margin: auto; margin-top: 2vh"
          :header-row-style="{
            height: '6vh',
            fontSize: '1vw',
            color: 'white',
            background: '#005EBC',
          }"
          :row-style="{ height: '12vh' }"
        >
          <el-table-column
            label="等级"
            prop="alarmName"
            align="center"
            min-width="20%"
          >
          </el-table-column>
          <el-table-column
            align="center"
            label="邮箱"
            prop="emailList"
            min-width="40%"
          >
            <template #default="scope">
              <div
                class="mailBox"
                v-if="scope.row.emailList && scope.row.emailList.length > 0"
              >
                <div
                  style="line-height: 3vh"
                  v-for="item in scope.row.emailList"
                >
                  {{ item }}
                </div>
              </div>
            </template></el-table-column
          >
          <el-table-column
            align="center"
            label="时间"
            prop="offlineMinutes"
            min-width="20%"
          ></el-table-column>
          <el-table-column
            label="编辑"
            prop="warningLong"
            align="center"
            min-width="20%"
          >
            <template #default="scope">
              <div
                style="color: #0baeef"
                @click="editOne(scope.row.id, scope.row.calss)"
              >
                编辑
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <div class="dialog" :style="{ display: dialog1 }">
        <div class="dialogInner">
          <div class="dialogInnerText" style="width: 47.5vw">
            <div class="dialogTop divCenter">
              <div class="dialogName">{{ addOrEdit }}告警/编辑</div>
              <div class="dialogClose divCenter" @click="close()"></div>
            </div>
            <div class="form">
              <div class="inputInner divCenter">
                <div class="deviceName">邮箱</div>
                <el-input
                  v-model="textArea"
                  type="textarea"
                  :rows="5"
                  placeholder="邮箱用英文逗号隔开"
                ></el-input>
              </div>
              <div class="inputInner divCenter">
                <div class="deviceName">告警上报时间</div>
                <el-input
                  style="width: 38vw"
                  v-model="warningSet.offlineMinutes"
                ></el-input>
                <div class="warningTime">分钟</div>
              </div>
              <div
                class="dubleButton divCenter"
                style="margin-top: 5vh; padding-bottom: 6vh"
              >
                <div
                  class="cancelButton divCenter"
                  style="background: #d30000"
                  @click="close()"
                >
                  取消
                </div>
                <div class="sureButton divCenter" @click="sureEdit()">确定</div>
              </div>
            </div>
          </div>
        </div>
      </div>
      <div class="dialog" :style="{ display: dialog2 }">
        <div class="dialogInner">
          <div class="dialogInnerText">
            <div class="dialogTop divBeteewn">
              <div class="dialogName">{{ addOrEdit }}设备</div>
              <div class="dialogClose divCenter" @click="close()">X</div>
            </div>
            <div class="dialogTips divCenter">
              确定要删除 &nbsp{{ this.form.deviceName }} &nbsp吗？
            </div>
            <div class="dubleButton divCenter">
              <div class="cancelButton divCenter" @click="close()">取消</div>
              <div
                class="sureButton divCenter"
                style="background: red"
                @click="sureDelete"
              >
                确定
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import sendMessage from "@/mitt/sendMessage.js";
import service from "@/api/api";
import { splitEmails } from "@/mitt/warn.js";
export default {
  name: "",
  beforeRouteEnter(to, from, next) {
    sendMessage(5, "告警管理");
    next();
  },
  data() {
    return {
      select: null,
      dialog1: "none",
      dialog2: "none",
      addOrEdit: "",
      dataList: [],
      warningList: [],
      tableWidth: "",
      form: {
        mail: "",
        electId: "",
        type: "",
        place: "",
        net: "",
        MQTT: false,
        state: "",
      },
      warningSet: {
        alarmLevel: null,
        alarmLevelName: null,
        alaemName: "",
        emailList: [],
        id: null,
        idEnabled: true,
        offlineMinutes: null,
      },
      id: null,
      textArea: "",
      time: "",
    };
  },
  props: [],

  methods: {
    convertMinutesToHours(minutes) {
      // 确保输入是数字
      if (typeof minutes !== "number" || isNaN(minutes)) {
        return "0分钟";
      }

      // 处理负数情况
      if (minutes < 0) {
        return "0分钟";
      }

      const hours = Math.floor(minutes / 60);
      const remainingMinutes = minutes % 60;

      let result = "";

      if (hours > 0) {
        result += `${hours}小时`;
      }

      if (remainingMinutes > 0) {
        result += `${remainingMinutes}分钟`;
      }

      // 如果总分钟数为0
      if (result === "") {
        return "0分钟";
      }

      return result;
    },
    splitEmails(emailStr) {
      // 检查是否存在中文逗号
      if (
        emailStr.includes("，") ||
        emailStr.includes("。") ||
        emailStr.includes("：") ||
        emailStr.includes(":")
      ) {
        this.$message({
          message: "邮箱只能用英文逗号隔开,请检查后提交",
          type: "warning",
        });
      } else if (!emailStr) {
        return [];
      }

      // 按英文逗号分割并过滤空项
      return emailStr
        .split(",")
        .map((item) => item.trim())
        .filter((item) => item.length > 0);
    },

    sureEdit() {
      console.log(this.textArea);
      this.warningSet.emailList = this.splitEmails(this.textArea);
      if (!this.warningSet.offlineMinutes) {
        this.getWarnSet();
        this.close();
        return this.$message({
          message: "告警上报时间不可缺少",
          type: "warning",
        });
      }
      if (this.warningSet.emailList.length == 0) {
        delete this.warningSet.emailList;
      }
      console.log(this.warningSet);

      service({
        method: "put",
        url: "/alarm",
        data: this.warningSet,
      })
        .then((e) => {
          console.log(e);
          if (e.status == "SUCCESS") {
            this.close();
            this.$message({
              message: "修改成功",
              type: "success",
            });
          } else {
            this.close();
            this.$message({
              message: response.data.errors[0].defaultMessage,
              type: "warning",
            });
          }
        })
        .catch((err) => {
          this.$message({
            message: err.data,
            type: "warning",
          });
        });
    },
    async getWarnSet() {
      let res = await service({
        method: "get",
        url: "/alarm/find-all",
      });
      this.warningList = res.data;
    },
    async getWarnList() {
      let res = await service({
        method: "get",
        url: "/report/device-warn",
      });
      console.log(res);
      if (res.status == "SUCCESS") {
        this.dataList = res.data;
      }
    },
    formatMail(a) {
      console.log(a);
      if (a && a.length > 0) {
        let res = "";
        a.forEach((item) => {
          res += `<div>${item}</div>`;
        });
        return res;
      }
    },
    skipPage(name) {
      this.$router.push({
        path: "/device",
        query: {
          name: name,
        },
      });
    },
    deleteOne(id, name) {
      this.dialog2 = "block";
      this.id = id;
      this.form.deviceName = name;
    },
    sureDelete() {
      this.dialog2 = "none";
    },
    clearChan() {},
    editOne(a, classL) {
      this.addOrEdit = classL;
      this.dialog1 = "block";
      this.warningList.forEach((item) => {
        if (item.id == a) {
          this.warningSet = item;
          console.log("this.warningSet", this.warningSet);
        }
      });
      try {
        if (this.warningSet.emailList.length > 0) {
          for (let i = 0; i < this.warningSet.emailList.length; i++) {
            if (i == this.warningSet.emailList.length - 1) {
              console.log(i);
              this.textArea += this.warningSet.emailList[i];
            } else {
              this.textArea += this.warningSet.emailList[i] + ",";
            }
          }
        } else {
          this.textArea = "";
        }
      } catch (error) {
        this.textArea = "";
      }
    },
    clear() {
      this.form = {
        deviceName: "",
        electId: "",
        type: "",
        place: "",
        net: "",
        MQTT: false,
        state: "",
      };
      this.id = null;
      this.warningSet = [];
      this.textArea = "";
    },
    addOne() {
      this.dialog1 = "block";
      this.addOrEdit = "新增";
    },
    close() {
      this.dialog1 = "none";
      this.dialog2 = "none";
      this.clear();
    },
    handClick() {
      console.log(11111);
    },
    handResize() {
      this.tableWidth = window.innerWidth - 150 + "px";
    },
    onSubmit() {
      console.log("submit!");
    },
    sendMessage() {
      let res = this.$route.path;
      EventBus.emit("custom-event", res);
    },
  },
  created() {
    this.handResize();
  },
  mounted() {
    // this.sendMessage();
    this.getWarnSet();
    this.getWarnList();
    window.addEventListener("resize", this.handResize);
  },
  beforeUnmount() {
    window.removeEventListener("resize", this.handResize);
  },
  beforeRouteLeave(to, from, next) {
    console.log("组件内守卫 - beforeRouteLeave", to.path);
    let res = to.path;

    next();
  },
};
</script>
<style lang="less" scoped>
.el-table {
  font-size: 1vw;
}

:deep(.el-textarea__inner) {
  font-size: 1vw;
  box-shadow: 0 0 0 1px #0281b8 inset;
  background: #efefef;
}
:deep(.el-input) {
  font-size: 1vw;
  box-shadow: 0 0 0 1px #0281b8 inset;
  background: #efefef;
  height: 4vh;
}
.el-input {
  height: 4.7vh;
}

:deep(.el-input__wrapper) {
  height: 4.7vh;
  background: #efefef !important;
}
// :deep(.el-table__row) {
//   border-bottom: 1px solid black;
// }
.warningLog {
  width: 120px;
  line-height: 35px;
  font-size: 18px;
  text-align: center;
  background: #00aeee;
}
.el-input {
  width: 100%;
  font-size: 1vw;
}
.warningBox {
  // width: 100%;
  height: 89vh;
  background: white;
  :deep(.el-table__cell) {
    padding: 0 !important;
    // border-bottom: 1px solid red;
  }
  :deep(.el-table td.el-table__cell) {
    border-bottom: 1px solid #a4a6a7;
  }
  :deep(.el-table tr:last-child td) {
    border-bottom: none;
  }

  :deep(.el-table__cell .cell) {
    display: flex;
    align-items: center;
    justify-content: center;
    // line-height: 3.5vh;
    height: 7vh !important;
    padding: 0 0;
    // height: 7vh !important;
    word-wrap: break-word;
    word-break: break-all;
    white-space: normal;
  }
}

.warningBox1 {
  // width: 100%;
  height: 89vh;
  background: white;
  :deep(.el-table__cell) {
    padding: 0 !important;
    // border-bottom: 1px solid red;
  }
  :deep(.el-table td.el-table__cell) {
    border-bottom: 1px solid #a4a6a7;
  }
  :deep(.el-table tr:last-child td) {
    border-bottom: none;
  }

  :deep(.el-table__cell .cell) {
    display: flex;
    align-items: center;
    justify-content: center;
    // line-height: 3.5vh;
    height: 10vh;
    padding: 0 0;
    // height: 7vh !important;
    word-wrap: break-word;
    word-break: break-all;
    white-space: normal;
  }
}

.warningNameBack {
  width: 10vw;
  line-height: 6vh;
  background: url(@/assets/img/top2.png);
  background-size: 100% 100%;
  font-size: 1.2vw;
  font-weight: 600;
  text-indent: 1em;
  font-family: smallMenu;
  color: white;
}
// :deep.el-form-item__content {
//   margin-left: 0 !important;
// }
.form {
  width: 90%;
  // height: 60vh;
  margin: auto;
  margin-top: 8vh;
  background: white;

  .inputInner {
    width: 100%;
    margin-bottom: 3.2vh;
    .deviceName {
      font-size: 1.2vw;
      font-weight: 400;
      width: 11.3vw;
      text-align: center;
      color: black;
    }
    .warningTime {
      width: 5vw;
      font-size: 1.2vw;
      text-indent: 1em;
    }
  }
}
.mailBox {
  width: 100%;
  height: 10vh;
  border: 1px solid #efefef;
  background: #efefef;
  overflow: auto;
  div {
    line-height: 1.5vh;
  }
}
.mailBox::-webkit-scrollbar {
  width: 5px; /* 自定义滚动条的宽度 */
  height: 5px; /* 如果需要自定义垂直滚动条的高度 */
}

/* 自定义滚动条滑块的颜色 */
.mailBox::-webkit-scrollbar-thumb {
  background-color: white;
  border-radius: 10px; /* 可选：为滚动条滑块添加圆角 */
}

/* 自定义滚动条轨道的颜色 */
.mailBox::-webkit-scrollbar-track {
  background-color: #f1f1f1;
  border-radius: 10px; /* 可选：为滚动条轨道添加圆角 */
}
.warningName {
  color: rgb(0, 94, 188);
}
</style>
